package src.com.neusoft.nep.controller;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import src.com.neusoft.nep.common.AlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;
import src.com.neusoft.nep.entity.ReceivedData;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

public class NepgTaskInformationViewController {
    @FXML
    private ImageView imageView;
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private DatePicker datePicker;

    @FXML
    private Label lb_feedbackUser, lb_grid, lb_location, lb_level, lb_description, lb_so2Level, lb_coLevel, lb_pmLevel, lb_aqiLevel;
    @FXML
    private TextField txt_so2, txt_co, txt_pm;
    @FXML
    private Button btn_taskInformationBack, btn_submitData;

    private ReceivedData receivedData;
    private Stage currentStage;
    private Map<String, ProvidedData> dataMap = new HashMap<>();

    public void setReceivedData(ReceivedData receivedData) {
        this.receivedData = receivedData;
        dataUpdate();
    }

    public void dataUpdate() {
        lb_feedbackUser.setText(receivedData.getUserName() + receivedData.getPhoneNumber());
        lb_level.setText(receivedData.getLevel());
        lb_grid.setText(receivedData.getProvince() + receivedData.getCity());
        lb_location.setText(receivedData.getLocation());
        lb_description.setText(receivedData.getDescription());
    }

    @FXML
    public void initialize() {
        Image image = new Image("/src/com/neusoft/nep/image/Nepg02.png");
        imageView.setImage(image);
        imageView.fitHeightProperty().bind(anchorPane.heightProperty());
        imageView.fitWidthProperty().bind(anchorPane.widthProperty());
        imageView.setPreserveRatio(false);
        imageView.setSmooth(true);

        //日期控件使用
        //设置默认值为当前系统时间
        datePicker.setValue(LocalDate.now());
        //添加监听时间，处理选择的时间
        datePicker.valueProperty().addListener(new ChangeListener<LocalDate>() {
            @Override
            public void changed(ObservableValue<? extends LocalDate> observableValue, LocalDate oldDate, LocalDate newDate) {
                System.out.println("选择的日期为：" + newDate);
            }
        });

        // 添加文本字段的监听器
        txt_so2.textProperty().addListener((observable, oldValue, newValue) -> updateLevels());
        txt_co.textProperty().addListener((observable, oldValue, newValue) -> updateLevels());
        txt_pm.textProperty().addListener((observable, oldValue, newValue) -> updateLevels());
    }

    public void setCurrentStage(Stage stage) {
        this.currentStage = stage;
    }

    public void backToTaskManageView() {
        if (currentStage != null) {
            currentStage.close();
        }
    }

    @FXML
    public void submitData() {
        // 读取现有的数据
        Map<String, ProvidedData> dataMap = FileUtils.readMapObject("AdminData.txt");
        // 获取当前日期
        LocalDate selectedDate = datePicker.getValue();

        // 创建新的 ProvidedData 对象
        ProvidedData providedData = new ProvidedData(receivedData.getProvince(), receivedData.getCity(), txt_so2.getText(), txt_co.getText(), txt_pm.getText(), selectedDate.toString(), NepgLoginViewController.getInstance().getLoggedInCode(), getAqiLevel(), receivedData.getUserName());
        //这里使用市作为key
        if (txt_so2.getText() == "" || txt_co.getText() == "" || txt_pm.getText() == ""){
            AlertUtils.showDialog("", "无效数据");
            return;
        }else {
            dataMap.put(receivedData.getCity(), providedData);
            // 将更新后的数据写回文件
            FileUtils.writeMapObject("AdminData.txt", dataMap);
            System.out.println("数据已保存到 AdminData.txt 文件中。");
            AlertUtils.showDialog("", "提交成功！");
            currentStage.close();
        }
    }

    //为浓度和AQI数据制作动态标签
    private int getLevel(double value, String type) {
        switch (type) {
            case "so2":
                if (value <= 50) return 1;
                else if (value <= 150) return 2;
                else if (value <= 475) return 3;
                else if (value <= 800) return 4;
                else if (value <= 1600) return 5;
                else return 6;
            case "co":
                if (value <= 5) return 1;
                else if (value <= 10) return 2;
                else if (value <= 35) return 3;
                else if (value <= 60) return 4;
                else if (value <= 90) return 5;
                else if (value <= 150) return 6;
                else return 6;
            case "pm":
                if (value <= 35) return 1;
                else if (value <= 75) return 2;
                else if (value <= 115) return 3;
                else if (value <= 150) return 4;
                else if (value <= 250) return 5;
                else if (value <= 500) return 6;
                else return 6;
            case"aqi":
                if (value == 1) return 1;
                else if (value == 2) return 2;
                else if (value == 3) return 3;
                else if (value == 4) return 4;
                else if (value == 5) return 5;
                else if (value == 6) return 6;
            default:
                return 0;
        }
    }
    private void updateLevels() {
        double so2 = 0.0;
        double co = 0.0;
        double pm = 0.0;

        try {
            so2 = Double.parseDouble(txt_so2.getText());
            co = Double.parseDouble(txt_co.getText());
            pm = Double.parseDouble(txt_pm.getText());
        } catch (NumberFormatException e) {
            resetLabels();
            return;
        }

        updateLabel(lb_so2Level, getLevel(so2, "so2"));
        updateLabel(lb_coLevel, getLevel(co, "co"));
        updateLabel(lb_pmLevel, getLevel(pm, "pm"));

        int so2Level = getLevel(so2, "so2");
        int coLevel = getLevel(co, "co");
        int pmLevel = getLevel(pm, "pm");

        double maxValue = Math.max(Math.max(so2Level, coLevel), pmLevel);
        updateLabel(lb_aqiLevel, getLevel(maxValue, "aqi"));
        int apiLevel = getLevel(maxValue, "aqi");
    }

    private void resetLabels() {
        // 重置样式
        lb_so2Level.setStyle("");
        lb_coLevel.setStyle("");
        lb_pmLevel.setStyle("");
        lb_aqiLevel.setStyle("");
    }

    private void updateLabel(Label label, int level) {
        String levelText = getLevelText(level);
        label.setText(levelText);

        // 根据等级设置不同的背景颜色
        switch (level) {
            case 1:
                label.setStyle("-fx-background-color: #00E400; -fx-text-fill: white; -fx-padding: 2px 5px;");
                break;
            case 2:
                label.setStyle("-fx-background-color: #FFFF00; -fx-text-fill: black; -fx-padding: 2px 5px;");
                break;
            case 3:
                label.setStyle("-fx-background-color: #FF7E00; -fx-text-fill: white; -fx-padding: 2px 5px;");
                break;
            case 4:
                label.setStyle("-fx-background-color: #FF0000; -fx-text-fill: white; -fx-padding: 2px 5px;");
                break;
            case 5:
                label.setStyle("-fx-background-color: #99004C; -fx-text-fill: white; -fx-padding: 2px 5px;");
                break;
            case 6:
                label.setStyle("-fx-background-color: #7E0023; -fx-text-fill: white; -fx-padding: 2px 5px;");
                break;
            default:
                label.setStyle("");
        }

        if (label == lb_aqiLevel){
            label.setText("实测AQI等级: " + levelText);
        }
    }

    private String getLevelText(int level) {
        switch (level) {
            case 1: return "一";
            case 2: return "二";
            case 3: return "三";
            case 4: return "四";
            case 5: return "五";
            case 6: return "六";
            default: return "未知";
        }
    }

    private String getAqiLevel() {
        return lb_aqiLevel.getText();
    }
}
